import { reactive, onMounted, defineComponent, toRefs, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import userApi from '@/api/system/user-api'
import ZlrtTable from '@/components/zlrt-table/table.vue'
import ZlrtSearch from '@/components/zlrt-search/search.vue'
import TableContext from '@/components/zlrt-table/table-context'
import roleApi from '@/api/system/role-api'
export default defineComponent({
  components: {
    ZlrtTable,
    ZlrtSearch
  },
  setup() {
    const disabledOptions = [
      { label: '正常', value: false },
      { label: '停用', value: true }
    ]

    const ctx = reactive(new TableContext(getCurrentInstance(), {
      title: '用户',
      api: userApi,
      columns: [
        { prop: 'username', label: '用户账号', valueType: 'input' },
        { prop: 'nickname', label: '用户名称', valueType: 'input' },
        { prop: 'phone', label: '手机号'},
        { prop: 'email', label: '邮箱' },
        { prop: 'disabled', label: '状态', slot: true, valueType: 'select', options: disabledOptions, permit: ['core:user:save'] },
        { prop: 'operation', label: '操作', slot: true }
      ],
      // 表单校验项规则
      rules: {
        username: [{ required: true, message: '请输入用户账号', trigger: 'blur' }],
        // password: [{ required: editAction === '新增', message: '请输入密码', trigger: 'blur' }],
        nickname: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
        disabled: [{ required: true, message: '请选择状态', trigger: 'change' }]
      },
      other: {
        // 状态切换
        statusChanged: (row) => {
          const { username, disabled } = row
          ElMessageBox.confirm(`确认要${disabled ? '停用' : '启用'}"${username}"${ctx.title}吗？`, '温馨提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            draggable: true
          })
            .then(async () => {
              const res = await userApi.save(row)
              if (res.success) {
                ElMessage.success(`${disabled ? '停用' : '启用'}成功`)
              } else {
                row.disabled = !disabled
              }
            })
            .catch(() => {
              row.disabled = !disabled
            })
        },
        setRoles() {
          const arr = []
          data.roleOptions.map(item => {
            const index = ctx.editData.role.findIndex(id => id === item.id)
            if(index > -1) {
              arr.push(item);
            }
          })
          Object.assign(ctx.editData, {
            roles: arr
          })
        },
        async showEdit(row) {
          const { id } = row
          const res = await userApi.detail(id);
          ctx.editData = res.data
          ctx.editData.role = []
          const roles =  ctx.editData.roles;
          if(roles && roles.length > 0) {
            const arr = [];
            roles.map(role => {
              arr.push(role.id)
            })
            Object.assign(ctx.editData, {
              role: arr
            })
          }
          ctx.editVisible = true;
        },
        // getRoles(row) {
          
          
        //   // console.log(row)
        //   // ctx.editData.role = arr;
        // }
      }
    }))

    const data = reactive({
      ctx,
      disabledOptions,
      roleOptions: []
    })

    const getRole = async () => {
      const params = {filter: { disabled: false }}
      const res = await roleApi.list(params)
      if (res.success) {
        data.roleOptions = res.data?.records
      }
    }

    // init
    onMounted(() => {
      getRole()
      ctx.loadData()
    })

    return {
      ...toRefs(data)
    }
  }
})
